// 将此文件内容复制到App.js，运行npm start即可查看效果。
import React, { useCallback } from 'react';
import { ReactFlow, Handle, useNodesState, useEdgesState, addEdge } from 'reactflow';
import 'reactflow/dist/style.css';
import { FiDatabase, FiCloud } from 'react-icons/fi';
import { toast, Toaster } from 'react-hot-toast'; // 添加Toast组件


// 自定义节点组件 npm install react-hot-toast
const CustomNode = ({ id, data, selected }) => {
  return (
    <div className={`custom-node ${selected ? 'selected' : ''}`}>
      <Handle
        type="target"
        position="top"
        className="!bg-teal-500"
        // isValidConnection={(connection) => 
        //   connection.source !== id  // 禁止自连接
        // }
      />
      
      <div className="node-header">
        <FiCloud className="node-icon" />
        <h3 className="node-title">{data.label}</h3>
      </div>
      <div className="node-body">
        <FiDatabase className="node-icon" />
        <span className="node-info">{data.content}</span>
      </div>

      <Handle
        type="source"
        position="bottom"
        className="!bg-purple-500"
      />
      
      <Handle
        type="source"
        position="right"
        id={`${id}-output-2`}
        className="!bg-pink-500"
        style={{ top: '30%' }}
      />
    </div>
  );
};

const initialNodes = [
  { 
    id: '1', 
    position: { x: 0, y: 0 }, 
    data: { 
      label: '开始节点',
      content: '输入数据源'
    },
    type: 'custom',
  },
  { 
    id: '2', 
    position: { x: 200, y: 150 }, 
    data: { 
      label: '处理节点',
      content: '数据处理流程'
    },
    type: 'custom',
  },
];

const initialEdges = [{ 
  id: 'e1-2', 
  source: '1', 
  target: '2',
  animated: true,
  style: { stroke: '#94a3b8' },
}];

const nodeTypes = {
  custom: CustomNode,
};

// 节点样式
const nodeStyle = `
  .custom-node {
    background: linear-gradient(145deg, #ffffff, #f1f5f9);
    border-radius: 8px;
    border: 2px solid #cbd5e1;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    padding: 16px;
    min-width: 200px;
    transition: all 0.2s ease;
  }

  .custom-node.selected {
    border-color: #6366f1;
    box-shadow: 0 4px 15px rgba(99, 102, 241, 0.2);
  }

  .custom-node:hover {
    transform: translateY(-2px);
  }

  .node-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    border-bottom: 1px solid #e2e8f0;
    padding-bottom: 8px;
  }

  .node-title {
    margin: 0;
    font-size: 1.1rem;
    color: #1e293b;
    margin-left: 8px;
  }

  .node-body {
    display: flex;
    align-items: center;
    color: #64748b;
  }

  .node-icon {
    font-size: 1.2rem;
    margin-right: 8px;
    color: #6366f1;
  }

  .node-info {
    font-size: 0.9rem;
  }

  .react-flow__handle {
    width: 14px;
    height: 14px;
    border-radius: 3px;
    border: none;
  }
`;

export default function App() {
  // 使用useNodesState管理节点状态
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
  // 连接处理回调
  const onConnect = useCallback(
    (connection) => {
      // 根据不同的输出端口设置边样式
      const edgeStyle = connection.sourceHandle?.endsWith('-output-2') 
        ? { stroke: '#ec4899' } 
        : { stroke: '#94a3b8' };

      return setEdges((eds) =>
        addEdge({
          ...connection,
          animated: true,
          style: edgeStyle,
        }, eds)
      );
    },
    [setEdges]
  );

  // 连接验证逻辑
  const isValidConnection = useCallback(
    (connection) => {
      // 禁止自连接
      if (connection.source === connection.target) {
        toast.error('不能连接到自身');
        // alert('不能连接到自身');
        return false;
      }

      // 检查目标节点是否已有连接
      const targetConnections = edges.filter(
        (edge) => edge.target === connection.target
      );

      if (targetConnections.length > 0) {
        toast.error('目标节点已有连接');
        console.log(`连接被禁止：节点 ${connection.target} 已有输入连接`);
        return false;
      }

      return true;
    },
    [edges]
  );


  return (
    <div style={{ height: '100vh', background: '#f8fafc' }}>
      <style>{nodeStyle}</style>
      <Toaster position="top-right" /> {/* Toast消息容器 */}
      <ReactFlow 
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}  // 添加状态变更处理器
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        nodeTypes={nodeTypes}
        isValidConnection={isValidConnection}
        fitView
        style={{ background: '#f8fafc' }}
        connectionLineStyle={{ stroke: '#94a3b8', strokeWidth: 2 }}
        defaultEdgeOptions={{
          type: 'smoothstep',
          animated: true,
          style: { strokeWidth: 2 }
        }}
      />
    </div>
  );
}
